package java_thinking.unit_18_IO._18_10;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * @Desc:   返回一个包含缓冲器中所有字符的字符串；
 * @author: cww
 * @DateTime: 2019/5/17 9:04
 */

public class BufferToText {
    private static final int BSIZE = 1024;
    private static String file1 = "src/maindemo/java/java_thinking/unit_18_IO/_18_10/GetChannelTransfer1.txt";
    public static void main(String[] args) throws IOException {
        FileChannel fc = new FileOutputStream(file1).getChannel();
        fc.write(ByteBuffer.wrap("Some text".getBytes()));
        fc.close();
        fc = new FileInputStream(file1).getChannel();
        ByteBuffer buff = ByteBuffer.allocate(BSIZE);
        fc.read(buff);
        buff.flip();
        //未能如期的运作,直接读字节，乱码
        System.out.println(buff.asCharBuffer());

        //返回到数据开始的地方
        buff.rewind();
        //获取系统编码
        String encoding = System.getProperty("file.encoding");
        //指定编码格式对ByteBuffer内容进行编码
        System.out.println("Decoded using " + encoding + "： " + Charset.forName(encoding).decode(buff));
        fc = new FileOutputStream(file1).getChannel();
        //写出时定义编码格式，就不会乱码了
        fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));
        fc.close();
        fc = new FileInputStream(file1).getChannel();
        buff.clear();
        fc.read(buff);
        buff.flip();
        System.out.println(buff.asCharBuffer());

        //用charBuffer 以某种编码往通道写,再进行读就不会乱码
        fc = new FileOutputStream(file1).getChannel();
        buff = ByteBuffer.allocate(24);
        buff.asCharBuffer().put("Some else");
        fc.write(buff);
        fc.close();
        fc = new FileInputStream(file1).getChannel();
        buff.clear();
        fc.read(buff);
        buff.flip();
        System.out.println(buff.asCharBuffer());
    }
}
